package com.cskaoyan.javase.network._1udp._v4;

import com.cskaoyan.javase.network.util.UDPNetworkUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 发送消息的线程要执行的任务
 *
 * @since 14:40
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class SendMsgTask implements Runnable {
    private DatagramSocket socket;
    // 发送任务的数据报包需要的目标IP地址和端口号
    private String targetIP;
    private int targetPort;


    public SendMsgTask(DatagramSocket socket, String targetIP, int targetPort) {
        this.socket = socket;
        this.targetIP = targetIP;
        this.targetPort = targetPort;
    }

    @Override
    public void run() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            String msg = sc.nextLine();
            try {
                DatagramPacket sendPacket = UDPNetworkUtils.getSendPacket(msg, targetIP, targetPort);
                socket.send(sendPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
